﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarolLib.Control;
using System.Xml;
using DispatchAssist.Service;
using System.Configuration;
using CarolLib;
using System.Web.Services.Protocols;
using System.Text.RegularExpressions;

namespace DispatchAssist.AppHost
{
    [ModuleContract("3395B2C7-FB0D-4BAF-B1B0-0D691762ED78", "系统管理", "信息模板管理")]
    public partial class MsgTemplateManage : MdiUserControl
    {
        RuleManagerService service = new RuleManagerService();
        DataTable dt = new DataTable();
        List<MsgTemplate> msgTemplateLst = null;

        int previewIndex = 0;

        public MsgTemplateManage()
            : base()
        {
            InitializeComponent();
        }
        public MsgTemplateManage(XmlNode node)
            : this()
        {
        }
        private void MsgTemplateManage_Load(object sender, EventArgs e)
        {

        }


        public override void Onload()
        {
            service.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();

            dgMsgTempList.MultiSelect = false;
            BindAlertActionDefines();
            grptMsgTempInfo.Visible = false;
            BindDataGrid();
            //cmbWarnLevel.SelectedIndex = 0;
            setControlsEnabled(false);
            try
            {
                if (cmbAlertAction.SelectedValue.ToString() == "32" || cmbAlertAction.SelectedValue.ToString() == "144")
                {
                    dt = service.GetConfigTempInfo("sms").Tables[0];
                    cmbTempInfo.DataSource = dt;
                }
                else
                {
                    dt = service.GetConfigTempInfo("nosms").Tables[0];
                    cmbTempInfo.DataSource = dt;
                }
                cmbTempInfo.DisplayMember = "key";
                cmbTempInfo.ValueMember = "value";
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

            base.Onload();
        }

        private void BindAlertActionDefines()
        {
            try
            {
                List<AlertActionDefine> checks = service.GetAllAlertActionDefineRecords().ToList<AlertActionDefine>();
                AlertActionDefine aad = new AlertActionDefine();
                aad.AlertActionFlag = -1;
                aad.AlertActionName = "请选择";
                checks.Insert(0, aad);
                this.cmbAlertAction.DataSource = checks;
                this.cmbAlertAction.DisplayMember = "AlertActionName";
                this.cmbAlertAction.ValueMember = "AlertActionFlag";

                //DataGridViewComboBoxCell cell = new DataGridViewComboBoxCell();
                //cell.Value = "0";
                //cell.DisplayMember = "未选择！";
                //this.cmbAlertAction.Items.Insert(0, cell);
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void BindDataGrid()
        {
            //dgAlertRuleList.DataSource = service.GetAllAlertRuleRecords().ToList<AlertRule>();
            //dgAlertRuleList.

            try
            {
                dgMsgTempList.Rows.Clear();

                msgTemplateLst = service.GetAllMsgTemplateRecords().ToList<MsgTemplate>();
                //dgAlertRuleList.Columns[0].

                int i = 0;
                foreach (MsgTemplate au in msgTemplateLst)
                {

                    DataGridViewRow row = new DataGridViewRow();
                    dgMsgTempList.Rows.Add(row);
                    //row.Cells["AlertRuleID"].Value = au.AlertRuleID;
                    dgMsgTempList.Rows[i].Cells[0].Value = au.MsgTemplateID;
                    dgMsgTempList.Rows[i].Cells[1].Value = AlertToActionName(au.AlertAction); //getAlertActionName(au.AlertAction);
                    dgMsgTempList.Rows[i].Cells[2].Value = au.MsgContent;
                    string viewacarsstr = "";
                    if (au.AlertAction == (int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.ManualSendAcrarsAlert || au.AlertAction == ((int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.AutoSendAcarsAlert | (int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.ConfirmAcars))
                    {
                        viewacarsstr = au.TargetType;
                    }
                    dgMsgTempList.Rows[i].Cells[3].Value = viewacarsstr;
                    i++;
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }


        }

        private string AlertToActionName(int alertAction)
        {
            int inputvalue = 0;
            if (alertAction == 4) inputvalue = 68;
            else if (alertAction == 16) inputvalue = 144;
            else { inputvalue = alertAction; }

            return getAlertActionName(inputvalue);
        }
        private string getAlertActionName(int alertAction)
        {
            List<AlertActionDefine> checks = service.GetAllAlertActionDefineRecords().ToList<AlertActionDefine>();
            AlertActionDefine aad = checks.Find(s => s.AlertActionFlag == alertAction);
            if (aad == null) { aad = new AlertActionDefine(); aad.AlertActionName = "未知"; }
            return aad.AlertActionName;
        }
        public static bool IsNotIncludedChinese(string str)
        {
            bool flag = false;
            if (!Regex.IsMatch(str, @"^[^\u4e00-\u9fa5]{0,}$"))
            {
                flag = false;
            }
            else
            {
                flag = true;
            }
            return flag;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {

            //service.
            try
            {
                string tagstr = (sender as Button).Tag.ToString();
                List<MsgTemplate> lst = service.GetAllMsgTemplateRecords().ToList<MsgTemplate>();

                MsgTemplate mt = lst.Find(s => s.AlertAction == (int)cmbAlertAction.SelectedValue);

                if (string.IsNullOrEmpty(richtxtMsgContent.Text))
                {
                    MessageBox.Show("请输入模板内容！");
                    return;
                }
                if (cmbTargetType.Visible == true && cmbTargetType.SelectedIndex == 0)
                {
                    MessageBox.Show("请选择ACARS类型！");
                    return;
                }
                if (cmbAlertAction.SelectedIndex == 0)
                {
                    MessageBox.Show("请选择警告方式！");
                    return;
                }

                if (cmbAlertAction.SelectedValue.ToString() == "8" || cmbAlertAction.SelectedValue.ToString() == "68")
                {

                    if (!IsNotIncludedChinese(this.richExMsgContent.Text))
                    {
                        MessageBox.Show("ACARS报文内容不能有汉字！");
                        richtxtMsgContent.Focus();
                        return;
                    }
                }


                MsgTemplate msgTemplate = null;
                if (tagstr == "create")
                {
                    if (mt != null)
                    {
                        MessageBox.Show("告警方式已经存在！");
                        return;
                    }
                    msgTemplate = new MsgTemplate();

                }
                else if (tagstr == "alter")
                {
                    msgTemplate = lst.Find(s => s.MsgTemplateID == ((Guid)(dgMsgTempList.CurrentRow.Cells[0].Value)));
                }

                msgTemplate.MsgContent = richtxtMsgContent.Text;

                msgTemplate.AlertAction = (int)(cmbAlertAction.SelectedValue);

                msgTemplate.TargetType = (cmbTargetType.Text).ToString(); ;

                msgTemplate.LastModifyTime = DateTime.Now;

                if (tagstr == "create")
                {
                    if (service.CreateMsgTemplate(msgTemplate))
                    {
                        MessageBox.Show("添加成功！");
                        grptMsgTempInfo.Visible = false;
                        BindDataGrid();
                        setControlsEnabled(false);

                        btnEdit.Enabled = true;
                        btnDelete.Enabled = true;
                        btnCreate.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("保存失败！");
                    }

                }
                else if (tagstr == "alter")
                {
                    if (service.UpdateMsgTemplate(msgTemplate))
                    {
                        MessageBox.Show("修改成功！");
                        grptMsgTempInfo.Visible = false;
                        int indexx = dgMsgTempList.CurrentRow.Index;
                        BindDataGrid();
                        dgMsgTempList.Rows[indexx].Selected = true;
                        dgMsgTempList.CurrentCell = dgMsgTempList.Rows[indexx].Cells[1];
                        dgMsgTempList_SelectionChanged(null, null);
                        setControlsEnabled(false);

                        btnEdit.Enabled = true;
                        btnDelete.Enabled = true;
                        btnCreate.Enabled = true;

                    }
                    else
                    {
                        MessageBox.Show("保存失败！");
                    }
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            btnSave.Tag = "create";
            setControlsEnabled(true);
            grptMsgTempInfo.Visible = true;
            setControlsEmpty();
            cmbAlertAction.Enabled = true;

            btnEdit.Enabled = false;
            btnDelete.Enabled = false;
            btnCreate.Enabled = false;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            btnSave.Tag = "alter";
            setControlsEnabled(true);
            grptMsgTempInfo.Visible = true;

            btnEdit.Enabled = false;
            btnDelete.Enabled = false;
            btnCreate.Enabled = false;

            cmbAlertAction.Enabled = false;

            richtxtMsgContent_TextChanged(null, null);

        }

        private void setControlsEnabled(bool boo)
        {
            richtxtMsgContent.Enabled = boo;
            cmbTargetType.Enabled = boo;
            cmbAlertAction.Enabled = boo;
            cmbTempInfo.Enabled = boo;
            btnInsert.Enabled = boo;
            btnSave.Enabled = boo;
            btnCancel.Enabled = boo;

            //dgMsgTempList.Enabled = !boo;
        }

        private void setBtnEnabled(bool boo)
        {
            btnDelete.Enabled = boo;
            btnCreate.Enabled = boo;
            btnEdit.Enabled = boo;
        }

        private void setControlsEmpty()
        {
            cmbAlertAction.SelectedIndex = 0;
            richtxtMsgContent.Text = "";
            cmbTargetType.SelectedIndex = 0;
            cmbTempInfo.SelectedIndex = 0;
        }


        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgMsgTempList.CurrentRow.Index < 0 || dgMsgTempList.CurrentRow.Index > msgTemplateLst.Count - 1)
            {
                MessageBox.Show("请选择一条警告规则！");
                return;
            }
            if (MessageBox.Show("确认删除此记录？", "删除确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return;
            }
            Guid msgTemplateID = new Guid((dgMsgTempList.CurrentRow.Cells["MsgTemplateID"].Value).ToString());
            try
            {
                if (service.DeleteMsgTemplate(msgTemplateID))
                {
                    MessageBox.Show("删除成功");
                    BindDataGrid();
                }
                else
                {
                    MessageBox.Show("删除失败");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }


        }
        private void dgMsgTempList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgMsgTempList.Rows.Count == 0) return;

            int index = dgMsgTempList.CurrentRow.Index;
            MsgTemplate msgTemplate = new MsgTemplate();

            bool flag = false;
            if (dgMsgTempList.Rows[index].Cells[0].Value == null) { if (msgTemplateLst.Count > 0) { if (index > msgTemplateLst.Count - 1) { msgTemplate = new MsgTemplate(); setBtnEnabled(false); } else { msgTemplate = msgTemplateLst[0]; setBtnEnabled(true); } } else { setBtnEnabled(true); return; } }
            else
            {
                Guid selectedID;
                if ((grptMsgTempInfo.Visible == true))
                {
                    if (MessageBox.Show("是否确定撤销当前编辑？", "确认框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        grptMsgTempInfo.Visible = false;

                        selectedID = (Guid)dgMsgTempList.Rows[index].Cells[0].Value; ;
                        dgMsgTempList.Rows[index].Selected = true;
                        setBtnEnabled(true);
                    }
                    else
                    {
                        grptMsgTempInfo.Visible = false;
                        selectedID = (Guid)dgMsgTempList.Rows[previewIndex].Cells[0].Value;
                        dgMsgTempList.Rows[previewIndex].Selected = true;
                        dgMsgTempList.CurrentCell = dgMsgTempList.Rows[previewIndex].Cells[1];
                        dgMsgTempList.ClearSelection();

                        grptMsgTempInfo.Visible = true;
                        setBtnEnabled(false);

                        if (btnSave.Tag.ToString() == "create")
                        {
                            flag = true;
                            btnCreate_Click(null, null);
                        }
                    }

                }
                else
                {
                    selectedID = (Guid)dgMsgTempList.Rows[index].Cells[0].Value;
                    dgMsgTempList.Rows[index].Selected = true;
                    setBtnEnabled(true);
                }

                msgTemplate = msgTemplateLst.Find(s => s.MsgTemplateID == selectedID);
                if (msgTemplate == null) msgTemplate = new MsgTemplate();

            }
            if (!flag)
            {
                cmbAlertAction.SelectedValue = msgTemplate.AlertAction;
                richtxtMsgContent.Text = msgTemplate.MsgContent;
                cmbTargetType.Text = msgTemplate.TargetType;
            }

        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            grptMsgTempInfo.Visible = false;
            if (btnSave.Tag.ToString() == "create")
            {
                dgMsgTempList.Rows[0].Selected = true;
                dgMsgTempList.CurrentCell = dgMsgTempList.Rows[0].Cells[1];
            }
            else if (btnSave.Tag.ToString() == "alter")
            {
                //dgAlertRuleList.Rows[dgAlertRuleList.CurrentRow.Index].Selected = true;

            }
            dgMsgTempList_SelectionChanged(null, null);
            setControlsEnabled(false);
            btnEdit.Enabled = true;
            btnDelete.Enabled = true;
            btnCreate.Enabled = true;
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            if (cmbTempInfo.SelectedIndex == 0)
            {
                MessageBox.Show("请选择一条模板单元！");
                return;
            }
            //string comment = "";

            int index = richtxtMsgContent.SelectionStart;
            richtxtMsgContent.Text = richtxtMsgContent.Text.Insert(richtxtMsgContent.SelectionStart, cmbTempInfo.SelectedValue.ToString());
            richtxtMsgContent.SelectionStart = index + cmbTempInfo.SelectedValue.ToString().Length;
            richtxtMsgContent.Focus();

            //if (dt != null)
            //{
            //    comment = GetCommentByKey(cmbTempInfo.Text, dt);
            //    index = richExMsgContent.SelectionStart;
            //    richExMsgContent.Text = richExMsgContent.Text.Insert(richExMsgContent.SelectionStart, comment);
            //    richExMsgContent.SelectionStart = index + comment.Length;
            //}

        }
        private string GetCommentByKey(string key, DataTable dt)
        {
            if (dt == null) return "";
            string comment = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["key"].ToString() == key) { comment = dt.Rows[i]["comment"].ToString(); break; }
            }

            return comment;
        }


        private void dgMsgTempList_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            previewIndex = e.RowIndex;
        }

        private void cmbAlertAction_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedValue = ((AlertActionDefine)((sender as ComboBox).SelectedItem)).AlertActionFlag;
            if (selectedValue == (int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.ManualSendAcrarsAlert || selectedValue == ((int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.AutoSendAcarsAlert | (int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.ConfirmAcars))
            {
                lblTargetType.Visible = true;
                cmbTargetType.Visible = true;
            }
            else
            {
                lblTargetType.Visible = false;
                cmbTargetType.Visible = false;
            }

            if (selectedValue == (int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.ManualSendSMSAlert || selectedValue == ((int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.AutoSendSMSAlert | (int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.ConfirmSMS))
            {
                dt = service.GetConfigTempInfo("sms").Tables[0];
                cmbTempInfo.DataSource = dt;
            }
            else
            {
                dt = service.GetConfigTempInfo("nosms").Tables[0];
                cmbTempInfo.DataSource = dt;
            }


        }



        private void richtxtMsgContent_TextChanged(object sender, EventArgs e)
        {
            // richExMsgContent.Text = richtxtMsgContent.Text;
            if (dt == null) { richExMsgContent.Text = richtxtMsgContent.Text; }
            else
            {
                string str = richtxtMsgContent.Text;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (str.Contains(dt.Rows[i]["value"].ToString()))
                    {
                        str = str.Replace(dt.Rows[i]["value"].ToString(), dt.Rows[i]["comment"].ToString());
                    }
                }

                richExMsgContent.Text = str;
            }
        }


    }
}
